package com.ruoyi.project.system.farmer.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.web.exception.DataException;
import com.ruoyi.project.system.base_family_info.domain.BaseFamilyInfo;
import com.ruoyi.project.system.base_family_info.mapper.BaseFamilyInfoMapper;
import com.ruoyi.project.system.function.domain.OverviewDB;
import com.ruoyi.project.system.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.system.farmer.mapper.FarmerMapper;
import com.ruoyi.project.system.farmer.domain.Farmer;
import com.ruoyi.project.system.farmer.service.IFarmerService;
import com.ruoyi.common.utils.text.Convert;

import javax.annotation.Resource;

/**
 * 农户管理Service业务层处理
 *
 * @author ssk
 * @date 2023-02-16
 */
@Service
public class FarmerServiceImpl implements IFarmerService
{
    @Autowired
    private FarmerMapper farmerMapper;
    @Resource
    private BaseFamilyInfoMapper baseFamilyInfoMapper;

    /**
     * 查询农户管理
     *
     * @param id 农户管理ID
     * @return 农户管理
     */
    @Override
    public Farmer selectFarmerById(Integer id)
    {
        //直接将需要的属性写到farmer里面，用时从另一个对象中拿
        Farmer farmer = farmerMapper.selectFarmerById(id);
        BaseFamilyInfo baseFamilyInfo = baseFamilyInfoMapper.selectBaseFamilyInfoByFid(farmer.getFid());
        farmer.setArea(baseFamilyInfo.getArea());
        farmer.setPhone(baseFamilyInfo.getPhone());
        farmer.setFamilyType(baseFamilyInfo.getFamilyType());
        farmer.setTwoArea(baseFamilyInfo.getTwoArea());
        farmer.setOtherArea(baseFamilyInfo.getOtherArea());
        return farmer;
    }

    /**
     * 查询农户管理列表
     *
     * @param farmer 农户管理
     * @return 农户管理
     */
    @Override
    public List<Farmer> selectFarmerList(Farmer farmer)
    {
        return farmerMapper.selectFarmerList(farmer);
    }

    /**
     * 新增农户管理
     *
     * @param farmer 农户管理
     * @return 结果
     */
    @Override
    public int insertFarmer(Farmer farmer) throws ParseException {
            farmer.setState(0);
            int flag = 0;
            if (farmer.getRegistrationTime() == null) {
                Date nowDate = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                Date date = null;
                try {
                    date = formatter.parse(formatter.format(nowDate));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                farmer.setRegistrationTime(date);
            }
            /**
             * TODO
             * 在此处应该有一个判断：
             * 如果relationship是户主，继续判断：
             *      查找户主表看看有没有此farmer的户编号，若已存在，则不允许添加此农户，返回前端应显示已有农户不允许添加，return
             *                                      若不存在，则在农户户主表和农户表分别添加上此农户即可，并在前端返回添加成功。return
             *  如果relationship不是户主：
             *      1. 查找此farmer的fid对应的户主，在此户主的户主表中修改area（耕地面积）为+=当前新增农户的area  PS：这个操作不确定是否需要执行，有待商议
             *      2. 在农户表中查找是否有此farmer的idCard，若有则提示已有此农户，无法添加，前端对应展示即可
             *                                          若没有 则在农户表中添加此农户即可
             *      3.若fid不存在，则提醒该户不存在
             */
        /*
        因此根据以上逻辑，以下这行代码应该在此farmer的relationship为户主且户主表中没有此户编号才会新建户主对象，而不是什么判断都没有的情况下，随便添加一个农户
        都新建了一个户主对象
         */
        String IdCard = farmer.getIdCard();
        Farmer farmer1 = farmerMapper.selectFarmByIdCard(IdCard);
        if(farmer1!=null){
            throw new DataException("该身份证已被注册!");
        }
        else{
            if (farmer.getRelationship() == 1) {
//            String fid=baseFamilyInfo.getFid();
//            OverviewDB overviewDB=new OverviewDB();
//            //设置表单中各个数据
//            overviewDB.setFid(fid);
//            overviewDB.setReportYear(2022);
//            overviewDB.setState(0);
//            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
//            Date date=new Date();
//            overviewDB.setOpTime(sdf.format(date));
//            //管理员账号
//            User currentUser = ShiroUtils.getSysUser();
//            // 获取当前的用户名称
//            overviewDB.setUserId(currentUser.getUserId());
//            farmerMapper.insertFarmerForm(overviewDB);
                String fid = farmer.getFid();
                BaseFamilyInfo baseFamilyInfo1 = baseFamilyInfoMapper.selectBaseFamilyInfoByFid(fid);
                if (baseFamilyInfo1 == null) {
                    BaseFamilyInfo baseFamilyInfo = new BaseFamilyInfo(farmer.getFid(), 1, farmer.getNatVillage(), farmer.getName(), farmer.getPhone(), farmerMapper.selectNumber(farmer.getFid()) + 1, farmer.getArea(), farmer.getTwoArea(), farmer.getOtherArea(), farmer.getFamilyType(), 0);
                    OverviewDB overviewDB=new OverviewDB();
                    //设置表单中各个数据
                    overviewDB.setFid(fid);
                    overviewDB.setReportYear(2022);
                    overviewDB.setState(0);
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                    Date date=new Date();
                    overviewDB.setOpTime(sdf.format(date));
                    //管理员账号
                    User currentUser = ShiroUtils.getSysUser();
                    // 获取当前的用户名称
                    overviewDB.setUserId(currentUser.getUserId());
                    farmerMapper.insertFarmerForm(overviewDB);
                    flag = (baseFamilyInfoMapper.insertBaseFamilyInfo(baseFamilyInfo) + farmerMapper.insertFarmer(farmer));
                }
//                else if(baseFamilyInfo1 == null&&farmer1 != null){
//                    throw new DataException("身份证已被注册！");
//                }
                else if(baseFamilyInfo1 != null&&baseFamilyInfo1.getState()==0){
                    throw new DataException("该户已存在户主！");
                }
                else if(baseFamilyInfo1 != null&&baseFamilyInfo1.getState()==1){
                    throw new DataException("该户已经销户，请使用其他户编号！");
                }
            }
            if (farmer.getRelationship() != 1) {
                String fid = farmer.getFid();
                BaseFamilyInfo baseFamilyInfo1 = baseFamilyInfoMapper.selectBaseFamilyInfoByFid(fid);
                if (baseFamilyInfo1 != null &&baseFamilyInfo1.getState()==0) {
//                    String IdCard = farmer.getIdCard();
//                    //通过前端传过来的idCard来找数据库已存的对象
//                    Farmer farmer1 = farmerMapper.selectFarmByIdCard(IdCard);
//                    if (farmer1 == null) {
//                    不是户主不需要新建一户
//                    BaseFamilyInfo baseFamilyInfo = new BaseFamilyInfo(farmer.getFid(),0,farmer.getNatVillage(),farmer.getName(),farmer.getPhone(),farmerMapper.selectNumber(farmer.getFid())+1,farmer.getArea(),farmer.getFamilyType(),0);
                        Integer num = farmerMapper.selectNumber(farmer.getFid()) + 1;
                        flag = farmerMapper.insertFarmer(farmer) + baseFamilyInfoMapper.updateBaseFamilyInfoNum(fid, num);
//                    }
//                    else {
////                    if (farmer1.getState() == 1) {
////                        Integer id = farmer1.getId();
////                        //返回值flag作为ajax发送请求的结果，为大于0时表明成功，所以别忘记给flag赋值
////                        flag = farmerMapper.updateFarmerByIdCard(id, farmer);
////                    } else
////                        {
//                        throw new DataException("该户已存在该人员！");
////                    }
//                    }
                }
                else if (baseFamilyInfo1 != null &&baseFamilyInfo1.getState()==1){
                    throw new DataException("该户已注销，无法加入新的户成员！");
                }
                else if(baseFamilyInfo1 == null){
                    throw new DataException("该户不存在！");
                }
            }}
            return flag;
        }

    /**
     * 修改农户管理
     *
     * @param farmer 农户管理
     * @return 结果
     */
    @Override
    public int updateFarmer(Farmer farmer) throws ParseException {
        int flag = 0;
        String newIdCard = farmer.getIdCard();
        Farmer farmer1 = farmerMapper.selectFarmByIdCard(newIdCard);
        Farmer oldFarmer0 = farmerMapper.selectFarmerById(farmer.getId());
        String oldIdCard = oldFarmer0.getIdCard();
        //说明证件号变了并且证件号已经存在了：
        if(farmer1!=null&& !Objects.equals(newIdCard, oldIdCard)) {
            throw new DataException("该身份证号已存在！");
        }
        else {
            //既然有该farm并且有id说明肯定没有被注销，oldfarm一定存在state一定为0
            Farmer oldFarmer = farmerMapper.selectFarmerById(farmer.getId());
            String oldfid = oldFarmer.getFid();
            String phone = farmer.getPhone();
            BigDecimal area = farmer.getArea();
            BigDecimal twoArea = farmer.getTwoArea();
            BigDecimal otherArea = farmer.getOtherArea();
            Integer familyType = farmer.getFamilyType();
            String newfid = farmer.getFid();
            //只有户主才可以改户编号，要是改变户编号，所有成员户编号都需要改变
            if (oldFarmer.getRelationship() == 1 && farmer.getRelationship() == 1 && oldfid.equals(newfid)) {
                flag = baseFamilyInfoMapper.updateBaseFamilyInfoByEdit(phone, area, familyType, twoArea, otherArea, oldfid) + farmerMapper.updateFarmer(farmer);
            } else if (oldFarmer.getRelationship() == 1 && farmer.getRelationship() == 1 && !newfid.equals(oldfid) && baseFamilyInfoMapper.selectBaseFamilyInfoByFid(newfid) == null) {
                flag = baseFamilyInfoMapper.updateBaseFamilyInfoByEdit1(phone, area, familyType, twoArea, otherArea,oldfid, newfid) + farmerMapper.updateFarmer(farmer) + farmerMapper.updateFarmerMemberByFid(oldfid, newfid);
            } else if (oldFarmer.getRelationship() == 1 && farmer.getRelationship() == 1 && !newfid.equals(oldfid) && baseFamilyInfoMapper.selectBaseFamilyInfoByFid(newfid) != null && baseFamilyInfoMapper.selectBaseFamilyInfoByFid(newfid).getState() == 0) {
                throw new DataException("该户编号已存在，请尝试其他户编号!");
            } else if (oldFarmer.getRelationship() == 1 && farmer.getRelationship() == 1 && !newfid.equals(oldfid) && baseFamilyInfoMapper.selectBaseFamilyInfoByFid(newfid) != null && baseFamilyInfoMapper.selectBaseFamilyInfoByFid(newfid).getState() == 1) {
                throw new DataException("该户编号已存在并且已经注销，请尝试其他户编号!");
            } else if (oldFarmer.getRelationship() == 1 && farmer.getRelationship() != 1) {
                throw new DataException("请转移户主之后再进行操作!");
            } else if (oldFarmer.getRelationship() != 1 && farmer.getRelationship() != 1) {
                flag = farmerMapper.updateFarmer(farmer);
            } else if (oldFarmer.getRelationship() != 1 && farmer.getRelationship() == 1) {
                throw new DataException("请转移户主之后再进行操作!");
            }
        }
        return flag;
    }

    /**
     * 删除农户管理对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteFarmerByIds(String ids)
    {
        return farmerMapper.deleteFarmerByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除农户管理信息
     *
     * @param id 农户管理ID
     * @return 结果
     */
    @Override
    public int deleteFarmerById(Integer id)
    {
        return farmerMapper.deleteFarmerById(id);
    }

    /**
     * 注销农户信息
     *
     * @param id 农户管理ID
     * @return 结果
     */
    //如果人口为1，直接注销
//    人口为2，若为户主请转移户主，若为普通农户则直接注销农户
    @Override
    public int logoutFarmerById(Integer id)
    {
        int flag = 0;
        Farmer farmer = farmerMapper.selectFarmerById(id);
        int number = farmerMapper.selectNumber(farmer.getFid());
        BaseFamilyInfo baseFamilyInfo = new BaseFamilyInfo();
        if (farmer.getRelationship() != 1){
            flag = farmerMapper.logoutFarmerById(id) + baseFamilyInfoMapper.logoutBaseFamilyInfoByFid(farmer.getFid());
        }
        else {
            if (number == 1){
                baseFamilyInfo = baseFamilyInfoMapper.selectBaseFamilyInfoByFid(farmer.getFid());
                baseFamilyInfo.setNum(baseFamilyInfo.getNum()-1);
                baseFamilyInfo.setState(1);
                flag = farmerMapper.logoutFarmerById(id) + baseFamilyInfoMapper.updateBaseFamilyInfo(baseFamilyInfo);
            }
            if (number > 2){
                flag = 0;
            }
        }
        return flag;
    }

    /**
     * 转移户主
     *
     * @param fid,oldName,newName,str 参数
     * @return 结果
     */
    @Override
    public int transferSave(String fid,String oldName, String newName,String str)
    {
        //判断是否选择多个新户主
        int house_hold = 0;
        Farmer farmer = new Farmer();
        String[] strArr = str.split(",");
        farmer.setFid(fid);
        farmer.setName(newName);
        List<Farmer> list = farmerMapper.selectFarmerList(farmer);
        farmer.setId(list.get(0).getId());

        Farmer[] farmers = new Farmer[10];
        int index = 0;
        for (int i=0;i<(strArr.length)/2;i++){
            Farmer ff = new Farmer();
            ff.setFid(fid);
            ff.setId(Integer.valueOf(strArr[index]));
            ff.setRelationship(Integer.valueOf(strArr[++index]));
            index++;
            farmers[i] = ff;
            //保证只有一个与户主关系为户主
            if (ff.getRelationship()==1){
                house_hold ++;
                //保证新户主姓名与户主关系统一
                if (ff.getId()!=farmer.getId()){
                    return 0;
                }
            }
        }
        if (house_hold > 1){
            return 0;
        }
        //如果与户主关系中没有户主
        if (house_hold == 0){
            return 0;
        }

        int flag = 0;
        BaseFamilyInfo baseFamilyInfo = new BaseFamilyInfo();

        baseFamilyInfo.setFid(fid);
        baseFamilyInfo.setName(newName);
        int num = baseFamilyInfoMapper.selectBaseFamilyInfoByFid(fid).getNum();
        num = num-1;
        baseFamilyInfo.setNum(num);
        flag += baseFamilyInfoMapper.updateBaseFamilyInfo(baseFamilyInfo);
        for (int i=0;i<num;i++){
            Farmer farmer1 = farmers[i];
            flag += farmerMapper.updateFarmer(farmer1);
        }
        flag += farmerMapper.updateHouseHoldState(fid,oldName);
        return flag;
    }

    /**
     * 查询户人口数与关系
     *
     * @param id 农户管理ID
     * @return 结果
     */
    @Override
    public HashMap selectNumShip(int id){
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        Farmer farmer = farmerMapper.selectFarmerById(id);
        map.put("number",farmerMapper.selectNumber(farmer.getFid()));
        map.put("relationship",farmer.getRelationship());
        return map;
    };

    /**
     * 查询家庭其他成员
     *
     * @param fid 户id
     * @return 农户信息集合
     */
    public List<Farmer> selectMember(String fid){
        return farmerMapper.selectMember(fid);
    }

    /**
     * 校验身份证号
     */
    public int checkIdCardUnique(String idCard){
        return farmerMapper.checkIdCardUnique(idCard);
    }

    @Override
    public Farmer getFarmerByName(String Name) {
        return farmerMapper.selectFarmByName(Name);
    }


}
